﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using BoYuanCore.DBServices.Base;
using BoYuanCore.Framework;
using BoYuanCore.Framework.Net;
using BoYuanCore.Web;
using FineUICore;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;


namespace BoYuanCore.WebUI.Areas.Admin.Controllers
{
    [Area("Admin")]
    public class LoginController : FineUICoreExtensions.FineUICoreController
    {
        private readonly ILogger<LoginController> _logger;
        private readonly IWebHostEnvironment _env;
        public IFreeSql DB = FreeSqlHelper.GetInstance();

        public LoginController(ILogger<LoginController> logger, IWebHostEnvironment env)
        {
            _logger = logger;
            _env = env;
        }

        public async Task<IActionResult> Index()
        {
            #if DEBUG
                        if (await LoginAsync("admin", "123456"))
                        {
                            return RedirectToAction("Index", "Home", new { area = "Admin" });//重定向到登陆后首页。这个跨域跳转是无效的。
                        }
            #endif
                      
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(IFormCollection fc)
        {
            //var ip = HttpHelper.GetTrueUserIP(); 
            string username = fc["u"].ToString().Trim();
            string pwd = fc["p"].ToString();

            try
            {
                if (! await LoginAsync(username,pwd) )
                {
                    await DBServices.SysLoginLog.AddLoginLogAsync(username, pwd, Entities.EnumClass.SysLoginLog.LoginState.登录失败);
                    AlertQuestion("账号密码错误,或此账号已冻结！");
                    return UIHelper.Result();
                }
              
                return RedirectToAction("Index", "Home", new { area = "Admin" });//重定向到登陆后首页。这个跨域跳转是无效的。
                //return RedirectToRoute("default", new { controller = "Home", action = "Index" });//跨域强制路由跳转

            }
            catch (Exception ex)
            {
                try
                {
                    await DBServices.SysLoginLog.AddLoginLogAsync(username, pwd, Entities.EnumClass.SysLoginLog.LoginState.登录异常, ex.Message);
                }
                catch (Exception exception)
                {
                    _logger.LogError("登录日志异常:" + exception.Message);
                }

                _logger.LogError("登录异常:" + ex.Message);
                AlertError("系统执行错误，请重试！");
                return UIHelper.Result();
            }
        }

        private async Task<bool> LoginAsync(string username, string pwd)
        {
            pwd = Security.MD5Helper.GetMd5Pwd(pwd);

            var admin =await DB.Select<Entities.SysAdmin, Entities.SysRole>()
                .LeftJoin((a, r) => a.RoleID == r.ID)
                .Where((a, r) => r.IsDel == false && a.IsDel == false && a.LoginName == username && a.Password == pwd)
                .FirstAsync((a, r) => a);

            if (admin == null)
            {
                return false;
            }

            await DBServices.SysLoginLog.AddLoginLogAsync(username, pwd, Entities.EnumClass.SysLoginLog.LoginState.登录成功, userid: admin.ID);

            //身份信息
            var claims = new[] {
                //new Claim("name", string.IsNullOrEmpty(admin.RealName)?admin.LoginName:admin.RealName),
                new Claim("userid", admin.ID.ToString())
            };
            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            ClaimsPrincipal userInfo = new ClaimsPrincipal(claimsIdentity);
            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                userInfo,
                new AuthenticationProperties()
                {
                    //https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/cookie?view=aspnetcore-2.1&tabs=aspnetcore2x
                    //https://www.cnblogs.com/sheldon-lou/p/9545726.html
                    //IsPersistent = true,//是否为永久性cookie(永不过期)。ExpiresUtc设置会使IsPersistent=true失效
                    ExpiresUtc = DateTime.UtcNow.AddHours(1)//默认1个小时过期(每次页面刷新会增加失效时间,跟session机制很像)
                });

            return true;
        }

       
    }
}